//
//  HadRealNameViewController.m
//  NewPro
//
//  Created by RYX on 2018/10/15.
//  Copyright © 2018年 何荧红. All rights reserved.
//

#import "HadRealNameViewController.h"
#import "FriendHeaderView.h"
#import "FriendCell.h"
#import "FriendSortView.h"
#import "FriendStore.h"
#import "FriendTableHeaderView.h"
#import "FriendModel.h"
#import "FriendList.h"

@interface HadRealNameViewController ()<UITableViewDelegate,UITableViewDataSource,FriendSortViewDelegate>
{
    NSString *currentKey;
    NSString *currentPx;
}
@property (nonatomic,strong) FriendHeaderView *headerView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) FriendSortView *sortView;
@property (nonatomic,strong) FriendTableHeaderView *tableHeaderView;

@property (nonatomic,strong) UIView *bgView;
@property (nonatomic,strong) NSMutableArray *sortArr;
@property (nonatomic,copy) NSArray *listArr;


@end

@implementation HadRealNameViewController

- (FriendTableHeaderView *)tableHeaderView{
    
    if (!_tableHeaderView) {
        
        _tableHeaderView = [[FriendTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
    }
    
    return _tableHeaderView;
}

- (NSMutableArray *)sortArr{
    
    if (!_sortArr) {
        
        NSArray *arr = @[@"合伙人规模从高到低",@"本月交易额从高到低",@"本月合伙人激活商户从多到少"];
        
        _sortArr = [NSMutableArray arrayWithArray:arr];
    }
    
    return _sortArr;
}
- (UIView *)bgView{
    
    if (!_bgView) {
        
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didBgView)]];
    }
    
    return _bgView;
}

- (void)didBgView{
    
    
    self.headerView.sortLa.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    self.headerView.sortIm.image = [UIImage imageNamed:@"theSort"];
    
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.25 animations:^{
        
        self.sortView.y = -100;
        self.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
    } completion:^(BOOL finished) {
        
        [self.bgView removeFromSuperview];
    }];
    
}


- (FriendSortView *)sortView{
    
    if (!_sortView) {
        
        _sortView = [[FriendSortView alloc] initWithFrame:CGRectMake(0, -100, ScreenWidth, 105)];
        _sortView.listArr = self.sortArr;
        _sortView.delegate = self;
        _sortView.backgroundColor = [UIColor whiteColor];
    }
    
    return _sortView;
}

- (FriendHeaderView *)headerView{
    
    if (!_headerView) {
        
        _headerView = [[[NSBundle mainBundle] loadNibNamed:@"FriendHeaderView" owner:self options:nil] objectAtIndex:0];
        
        MJWeakSelf
        __block HadRealNameViewController *  blockSelf = self;
        [_headerView setSortBlock:^{

            if ([blockSelf.headerView.sortLa.textColor isEqual:BLUECOLOR]) {
                
                return [weakSelf didBgView];
            }
            
            blockSelf.headerView.sortLa.textColor = BLUECOLOR;
            blockSelf.headerView.sortIm.image = [UIImage imageNamed:@"theSortTwo"];
            
            [weakSelf.view insertSubview:weakSelf.bgView belowSubview:weakSelf.sortView];
            
            [UIView animateWithDuration:0.25 animations:^{
                
                weakSelf.sortView.y = 106;
                weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
            }];
        }];
    }
    
    return _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    currentPx = @"0";
    
    [self.view insertSubview:self.headerView atIndex:1];
    
    
    [self.view insertSubview:self.tableView atIndex:0];
    
    [self.view insertSubview:self.sortView belowSubview:self.headerView];
    
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(106);
        make.left.right.top.equalTo(self.view).offset(0);
        
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.headerView.mas_bottom).offset(1);
        make.left.right.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(-(TAB_BAR_HEIGHT) - (45));
    }];
    
    [self.tableView.mj_header beginRefreshing];
    
    //来自检索姓名的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSearch:) name:@"HadRealName" object:nil];
    
    //来自个人中心上传完头像的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"refreshUI" object:nil];
    
}

- (void)onSearch:(NSNotification *)noti{
    
    if ([FriendList sharedInstance].flag == 1) {
        
        return;
    }
    [self.view endEditing:YES];
    NSDictionary *dic = [noti userInfo];
    
    currentKey = [dic objectForKey:@"searText"];
    if ([[dic objectForKey:@"searText"] isEqualToString:@"no search"]) {
        
        currentKey = @"";
    }
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)refresh{
    
    FriendStore *store = [[FriendStore alloc] init];
    
    MJWeakSelf
    [store getFriendListWithCustomId:[UserDefaultsManager sharedInstance].user_id andType:@"1" andKey:currentKey andPx:currentPx Success:^(NSArray *listArr, NSString *headImg,NSString *name,NSString *leve) {
        
        weakSelf.listArr = listArr;
        
        if (self->currentKey.length > 0) {
            
            NSMutableArray *arr = [NSMutableArray array];
            
            for (FriendModel *model in listArr) {
                
                if ([model.realName rangeOfString:self->currentKey].location != NSNotFound){
                    
                    [arr addObject:model];
                }
            }
            
            weakSelf.listArr = arr;
        }
        
        weakSelf.tableHeaderView.numLa.text = [NSString stringWithFormat:@"    合伙人 共%lu人",(unsigned long)listArr.count];
        
        if (name.length > 0) {
            
            weakSelf.headerView.namLa.text = name;
        }
        
        if ([leve integerValue] > 0) {
            
            NSString *img = [NSString stringWithFormat:@"等级%ld",(long)[leve integerValue]];
            weakSelf.headerView.leveIm.image = [UIImage imageNamed:img];
        }else{
            
            weakSelf.headerView.leveIm.image = [UIImage imageNamed:@""];
        }
        
        [weakSelf.headerView.headImg sd_setImageWithURL:[NSURL URLWithString:headImg] placeholderImage:[UIImage imageNamed:@"头像"]];
        
        [weakSelf.tableView reloadData];
        
        [weakSelf.tableView.mj_header endRefreshing];
        
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.tableHeaderView;
        [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        
        MJWeakSelf
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [weakSelf refresh];
        }];
        
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
    }
    
    return _tableView;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [FriendCell getHeight];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FriendCell *cell = [FriendCell tempWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell reviveInfoWithModel:self.listArr[indexPath.row] andFlag:0 andType:[currentPx intValue]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    FriendModel *model = self.listArr[indexPath.row];
    if (self.subSN.count > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"FriendAlert" object:model];
        return;
    }
    NSString *str = [NSString stringWithFormat:@"tel:%@",model.phoneNumber];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}
#pragma mark - FriendSortViewDelegate
- (void)onCell:(NSInteger)row{

    NSString *cuurentTitle = self.headerView.sortLa.text;
    
    [self didBgView];
    
    self.headerView.sortLa.text = self.sortArr[row];
    
    currentKey = @"";
    
    if ([self.sortArr[row] isEqualToString:@"默认排序"]) {
        
        currentPx = @"0";
    }else if ([self.sortArr[row] isEqualToString:@"合伙人规模从高到低"]) {
        
        currentPx = @"1";
    }else if ([self.sortArr[row] isEqualToString:@"本月交易额从高到低"]) {
        
        currentPx = @"2";
    }else if ([self.sortArr[row] isEqualToString:@"本月合伙人激活商户从多到少"]){
        
        currentPx = @"3";
    }
    self.headerView.sortLa.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    //self.headerView.sortIm.image = [UIImage imageNamed:@"theSort"];
    
    [self.sortArr replaceObjectAtIndex:row withObject:cuurentTitle];
    
    self.sortView.listArr = self.sortArr;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DidScroll" object:nil];
}
@end
